package com.meisen.springboot.util;

import com.meisen.springboot.exception.ServerException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密算法
 * MD5加密算法
 *
 * @author meisen
 * 2018-04-17
 */
public class Encrypt {

    private static final String MD5_STR = "MD5";

    public static final String SALT = "*$^jis";

    public static String encrypt(String source) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance(MD5_STR);
        } catch (NoSuchAlgorithmException e) {
            throw new ServerException(2, "[系统错误], 无法加密!");
        }
        messageDigest.update((source + SALT).getBytes());
        byte[] bytes = messageDigest.digest();
        int temp;
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            temp = aByte;
            if (temp < 0) temp += 256;
            if (temp < 16) sb.append("0");
            sb.append(Integer.toHexString(temp));
        }
        return  sb.toString();
    }
}
